package com.yupi.springbootinit.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.springbootinit.common.BaseResponse;
import com.yupi.springbootinit.common.ResultUtils;
import com.yupi.springbootinit.model.entity.McMessage;
import com.yupi.springbootinit.model.entity.McMessageDelivery;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.mapper.McMessageMapper;
import com.yupi.springbootinit.mapper.McMessageDeliveryMapper;
import com.yupi.springbootinit.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/message")
public class MessageController {

    @Resource
    private UserService userService;
    @Resource
    private McMessageDeliveryMapper deliveryMapper;
    @Resource
    private McMessageMapper messageMapper;

    public static record MarkReadRequest(List<Long> ids) {}
    public static record MessageItem(
            Long messageId,
            String eventId,
            String type,
            String title,
            String content,
            String severity,
            Date createdAt,
            Long deliveryId,
            String deliveryStatus,
            Date readAt
    ) {}

    @GetMapping("/unread/count")
    public BaseResponse<Map<String, Object>> unreadCount(HttpServletRequest request) {
        User login = userService.getLoginUser(request);
        QueryWrapper<McMessageDelivery> qw = new QueryWrapper<McMessageDelivery>()
                .eq("receiver_type", "USER")
                .eq("receiver_id", login.getId())
                .eq("status", "UNREAD");
        Long cnt = deliveryMapper.selectCount(qw);
        return ResultUtils.success(Map.of("count", cnt == null ? 0 : cnt));
    }

    @GetMapping("/list")
    public BaseResponse<Map<String, Object>> list(
            HttpServletRequest request,
            @RequestParam(defaultValue = "ALL") String status,
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int pageSize
    ) {
        User login = userService.getLoginUser(request);
        current = Math.max(1, current);
        pageSize = Math.min(Math.max(1, pageSize), 100);

        QueryWrapper<McMessageDelivery> qw = new QueryWrapper<McMessageDelivery>()
                .eq("receiver_type", "USER")
                .eq("receiver_id", login.getId());
        if (!"ALL".equalsIgnoreCase(status)) {
            qw.eq("status", status.toUpperCase(Locale.ROOT));
        }
        qw.orderByDesc("id");

        Page<McMessageDelivery> page = new Page<>(current, pageSize);
        Page<McMessageDelivery> result = deliveryMapper.selectPage(page, qw);
        List<McMessageDelivery> deliveries = result.getRecords();
        if (deliveries.isEmpty()) {
            return ResultUtils.success(Map.of(
                    "total", result.getTotal(),
                    "records", List.of()
            ));
        }

        // 批量取消息
        List<Long> messageIds = deliveries.stream().map(McMessageDelivery::getMessageId).filter(Objects::nonNull).toList();
        if (messageIds.isEmpty()) {
            return ResultUtils.success(Map.of(
                    "total", result.getTotal(),
                    "records", List.of()
            ));
        }
        QueryWrapper<McMessage> mqw = new QueryWrapper<McMessage>().in("id", messageIds);
        List<McMessage> messages = messageMapper.selectList(mqw);
        Map<Long, McMessage> msgMap = messages.stream().collect(Collectors.toMap(McMessage::getId, m -> m));

        List<MessageItem> items = new ArrayList<>();
        for (McMessageDelivery d : deliveries) {
            McMessage m = msgMap.get(d.getMessageId());
            if (m == null) continue;
            items.add(new MessageItem(
                    m.getId(),
                    m.getEventId(),
                    m.getType(),
                    m.getTitle(),
                    m.getContent(),
                    m.getSeverity(),
                    m.getCreatedAt(),
                    d.getId(),
                    d.getStatus(),
                    d.getReadAt()
            ));
        }

        return ResultUtils.success(Map.of(
                "total", result.getTotal(),
                "records", items
        ));
    }

    @PostMapping("/markRead")
    public BaseResponse<Map<String, Object>> markRead(HttpServletRequest request, @RequestBody MarkReadRequest body) {
        User login = userService.getLoginUser(request);
        List<Long> ids = (body == null || body.ids() == null) ? List.of() : body.ids();
        if (ids.isEmpty()) {
            return ResultUtils.success(Map.of("ok", true, "updated", 0));
        }
        Date now = new Date();
        // 仅更新当前用户的投递
        QueryWrapper<McMessageDelivery> qw = new QueryWrapper<McMessageDelivery>()
                .in("id", ids)
                .eq("receiver_type", "USER")
                .eq("receiver_id", login.getId())
                .eq("status", "UNREAD");
        List<McMessageDelivery> target = deliveryMapper.selectList(qw);
        int updated = 0;
        for (McMessageDelivery d : target) {
            McMessageDelivery up = new McMessageDelivery();
            up.setId(d.getId());
            up.setStatus("READ");
            up.setReadAt(now);
            up.setUpdatedAt(now);
            updated += deliveryMapper.updateById(up);
        }
        return ResultUtils.success(Map.of("ok", true, "updated", updated));
    }
}